package com.example.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import message.*;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.os.Message;

import com.example.silvercare.Coalition;
import com.example.silvercare.R;

public class GetSingleFriendLocation extends Activity {

	String latitude;
	String longitude;
	String address;
	String fingerprint;
	EditText Latitude;
	EditText Longitude;
	EditText Address;
	EditText Fingerprint;
	
	LocationManager mLocationManager;
	Location mLocation;
	LocationListener listener;
	
    String friendName;
    String friendEmail;
    
    String IpAddress;
    String Port;
    
    SharedPreferences myprefs;
    String myname;
    String myemail;
 
	final Handler UpdateHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {      
		             case 1:
		            	setCoordinates();
		            	setFingerprint();
		            	//QueryMapEngine();
			        	setAddress();
		                  break;      
		              }      
		              super.handleMessage(msg);  
		         }    
		     }; 
		     
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        setContentView(R.layout.location);
        
        friendName = getIntent().getStringExtra("FriendName");
        friendEmail = getIntent().getStringExtra("FriendEmail");
        this.setTitle(friendName+"'s Location");
        
        myprefs = PreferenceManager.getDefaultSharedPreferences(this);
        myname = myprefs.getString("namePref", null);
        myemail = myprefs.getString("emailaddressPref", null);
        
        Latitude = (EditText) findViewById(R.id.Lat);
        Longitude = (EditText) findViewById(R.id.Lon);
        Address = (EditText) findViewById(R.id.Addr);
        Fingerprint = (EditText) findViewById(R.id.Fingerprint);
        Button mapviewButton = (Button) findViewById(R.id.mapviewButton);
        
		latitude = "Waiting";
		longitude = "Waiting";
		address = "Waiting";
		fingerprint = "Waiting";
		
		IpAddress = "null";
		Port = "null";
		
		Thread t = new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				getFriendCurrentLocation();
			}
			
		});
        t.start();
        
		setCoordinates();
		setFingerprint();
		//QueryMapEngine();
		setAddress();
        
        mapviewButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent i = new Intent("com.example.server.MapViewActivity");
				i.putExtra("LATITUDE", latitude);
				i.putExtra("LONGITUDE", longitude);
				startActivity(i);
			}
        	
        });
	}
	
	//Query Map Engine and Get Address
	private void getFriendCurrentLocation(){
		/*
		if(getFriendConnectionInfo()==0)
		{
			 try {
	                Socket socket = new Socket(IpAddress,Integer.parseInt(Port));
	                //outgoing stream redirect to socket
	                message.Message msg1 = new message.Message();
	                msg1.setServiceType(0);
	                msg1.setContent(myname+"|"+myemail);
	                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
	                oos.writeObject(msg1);
	                
	                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
	                message.Message msg2 = (message.Message) ois.readObject();
	                if(msg2.getContent()!=null)
	                {
		        		latitude = msg2.getContent();
		        		longitude = "null";
		        		address = "null";
		        		//setCoordinates();
		        		//setFingerprint();
		        		//QueryMapEngine();
		        		//setAddress();
		        		Message message = new Message();      
						message.what = 1;      
						UpdateHandler.sendMessage(message); 
	                	Log.d("Tcp Example", "From server: "+msg2.getContent());
	                }
	                else
	                {
		        		latitude = "rejected";
		        		longitude = "rejected";
		        		address = "rejected";
		        		Message message = new Message();      
						message.what = 1;      
						UpdateHandler.sendMessage(message); 
	                	Log.d("Tcp Example", "From server: "+"null");
	                }
	        		
	                //Close connection
	                socket.close();

		        } catch (UnknownHostException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
		        } catch (IOException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
		        } catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}*/
		MapEngineClient mapEngine = new MapEngineClient();
		String result = mapEngine.processService(3, myname+"|"+myemail+"|none|"+friendEmail);
		if(result==null)
			System.out.println("Map Engine Return(1) NULL");
		else
		{
	        Scanner sc=new Scanner(result).useDelimiter("\\|");
			String s1,s2,s3,s4,s5,s6,s7;
			s1=sc.next();
			s2=sc.next();
			s3=sc.next();
			s4=sc.next();
			s5=sc.next();
			s6=sc.next();
			s7=sc.next();
			latitude = s2;
			longitude = s3;
			fingerprint = s4+","+s5+","+s6;
			address = s7;
    		Message message = new Message();      
			message.what = 1;      
			UpdateHandler.sendMessage(message); 
			System.out.println("Map Engine Return(1) "+result);
		}
		mapEngine.close();
	}
	
	//Request Ip address and port throught Coalition
	private int getFriendConnectionInfo(String email){
		String result = Coalition.getFriendConnectionInfo(email);
		if(result==null || !result.contains("|"))
			return -1;
		int mid = result.indexOf("|");
		String s1 = result.substring(0, mid);
		String s2 = result.substring(mid+1, result.length());
		if(s1 == null || s2 == null)
			return -1;
		IpAddress = s1;
		Port = s2;	
		return 0;
	}
	
	private void setCoordinates(){
        Latitude.setText(latitude);
        Longitude.setText(longitude);
	}
	private void setFingerprint(){
		Fingerprint.setText(fingerprint);
	}	
	private void setAddress(){
        Address.setText(address);
	}
	
	private void QueryMapEngine(){
		//sent latitude and longitude to map engine
		Thread initBkgThread = new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				//sent latitude and longitude to map engine

				MapEngineClient client = new MapEngineClient();
				client.close();
				address = "NUS SOC COM1";
				setAddress();
			}
			
		});
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

}
